package org.study.stream;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * parallelStream() 示例
 * 参考 https://blog.csdn.net/xuxiaoyinliu/article/details/73040808
 *
 * @author Administrator
 * @date 2022-12-30
 */
public class StreamTest08 {
    public static void main(String[] args) throws InterruptedException {
        test01();
        test02();
    }

    public static void test01() throws InterruptedException {
        Integer[] intArray = {1, 2, 3, 4, 5, 6, 7, 8};
        List<Integer> listOfIntegers = new ArrayList<>(Arrays.asList(intArray));
        List<Integer> parallelStorage = new ArrayList<>();
        listOfIntegers.parallelStream()
                // Don't do this! It uses a stateful lambda expression.
                .map(e -> {
                    parallelStorage.add(e);
                    return e;
                }).forEachOrdered(e -> System.out.print(e + " "));
        System.out.println();
        parallelStorage.stream().forEachOrdered(e -> System.out.print(e + " "));
        System.out.println("\nSleep 5 sec");
        TimeUnit.SECONDS.sleep(5);
        parallelStorage.stream().forEachOrdered(e -> System.out.print(e + " "));
        System.out.println();
    }

    public static void test02() throws InterruptedException {
        Integer[] intArray = {1, 2, 3, 4, 5, 6, 7, 8};
        List<Integer> listOfIntegers = new ArrayList<>(Arrays.asList(intArray));
        List<Integer> parallelStorage = Collections.synchronizedList(new ArrayList<>());
        listOfIntegers.parallelStream()
                .map(e -> {
                    parallelStorage.add(e);
                    return e;
                }).forEachOrdered(e -> System.out.print(e + " "));
        System.out.println();
        parallelStorage.stream().forEachOrdered(e -> System.out.print(e + " "));
        System.out.println("\nSleep 5 sec");
        TimeUnit.SECONDS.sleep(5);
        parallelStorage.stream().forEachOrdered(e -> System.out.print(e + " "));
        System.out.println();
    }
}
